package com.cn.shuangzi.view.pop.common;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.cn.shuangzi.util.SZTextViewWriterUtil;


/**
 ********************
 * 通用ViewHolder
 * @author cn
 ********************
 */
public class ViewHolder {
	private SparseArray<View> mViews;
	private View mConvertView;
	private int position;
	private Context context;
	public ViewHolder(Context context, int layoutId) {
		mViews = new SparseArray<>();
		this.context = context;
		mConvertView = LayoutInflater.from(context).inflate(layoutId, null);
		mConvertView.setTag(this);
	}
	public static ViewHolder getViewHolder(Context context, View convertView, int layoutId){
		if(convertView == null)
			return new ViewHolder(context,layoutId);
		return (ViewHolder) convertView.getTag();
	}
	@SuppressWarnings("unchecked")
	public <T extends View> T getView(int viewId){
		View item = mViews.get(viewId);
		if(item == null){
			item = mConvertView.findViewById(viewId);
			mViews.put(viewId, item);
		}
		return (T) item;
	}
	public View getMConvertView(){
		return mConvertView;
	}
	public int getPosition() {
		return position;
	}
	public void setPosition(int position) {
		this.position = position;
	}
	public ViewHolder setGone(int resId, boolean visible){
		getView(resId).setVisibility(visible? View.VISIBLE : View.GONE);
		return this;
	}
	public ViewHolder setInvisible(int resId, boolean visible){
		getView(resId).setVisibility(visible? View.VISIBLE : View.INVISIBLE);
		return this;
	}
	public ViewHolder setText(int resId, String value){
		SZTextViewWriterUtil.writeValue((TextView) getView(resId),value);
		return this;
	}
	public ViewHolder setTextWithGone(int resId, String value){
		SZTextViewWriterUtil.writeValueWithGone((TextView) getView(resId),value);
		return this;
	}
	public ViewHolder setTextDrawable(int resId, Drawable left, Drawable top, Drawable right, Drawable bottom){
		((TextView) getView(resId)).setCompoundDrawables(left,top,right,bottom);
		return this;
	}
	public ViewHolder setTextColor(int resId, int colorResId){
		((TextView) getView(resId)).setTextColor(context.getResources().getColor(colorResId));
		return this;
	}
	public ViewHolder setTextSize(int resId, int dimenResId){
		((TextView) getView(resId)).setTextSize(TypedValue.COMPLEX_UNIT_PX,context.getResources().getDimension
				(dimenResId));
		return this;
	}
	public ViewHolder setImageResource(int resId, int mippmapId){
		((ImageView)getView(resId)).setImageResource(mippmapId);
		return this;
	}
}
